﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using UnionistsManagement_DaLat.Areas.Admin.Models;

namespace UnionistsManagement_DaLat.Areas.Admin.CustomMemberShip
{
    public class CustomAuthorize:AuthorizeAttribute
    {
        private const string IS_AUTHORIZED = "isAuthorized";

        public string RedirectUrl = "~/Areas/Admin/Error/AccessDenied";

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("");
            }
            else
            {
                bool isAuthorized = base.AuthorizeCore(httpContext);

                httpContext.Items.Add(IS_AUTHORIZED, isAuthorized);

                return isAuthorized;
            }

        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {


            UnionistsManagementContext db = new UnionistsManagementContext();
            var user = db.Accounts.FirstOrDefault(x => x.Username == filterContext.HttpContext.User.Identity.Name);
            var role = user.Role.ID;
            var list = db.Accesses.Where(a=>a.Role.ID == role).ToList();
            var controller = filterContext.HttpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
            var action = filterContext.HttpContext.Request.RequestContext.RouteData.Values["action"].ToString();
            var check = true;

            foreach (var access in list)
            {
                string FunName = db.Functions.FirstOrDefault(x => x.ID == access.Function.ID).FunctionName;
                if (FunName.Contains(controller))
                {
                    if (FunName.Contains(action))
                    {
                        check = true;
                        break;
                    }
                    else
                    {
                        check = false;
                    }
                }
                else
                {
                    check = false;
                }

            }

            if (!check)
            {
                filterContext.Result = new RedirectToRouteResult(new
                           RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
            }
        }


        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectToRouteResult(new
                          RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}